<?php
namespace doumiaoduo\telecaptcha;

use yii\base\Action;
use yii\base\ActionEvent;
use yii\helpers\ArrayHelper;

class TelecaptchaAction extends Action
{
    public $telenumber = '';

    const EVENT_SEND_TELEPHONE_VALIDATE_CODE = 'sendtelephonevalidatecode';

    public $behaviorsData = [];
    /*
     * 点击获取验证码所进行的操作
     * 1. 获取手机号
     * 2. 生成随机验证码，以及短信内容
     * 3. 发送短信
     * 4. 成功之后保存短信码和事件至session中；失败返回错误信息
     */
    public function run()
    {
        $special_function = \Yii::$app->request->post('special_func');
        if($special_function == 'smscode'){
            $telenumber = \Yii::$app->request->post('telephone');
            /*
             * 1. 一分钟之内提交，直接失败返回
             */
            $maxcount_code = 5;
            $currenttime = time();
            $sessiontime = \Yii::$app->session->get('login_sms_time') ? \Yii::$app->session->get('login_sms_time') : 0;
            $durationtime = $currenttime - $sessiontime;
            if ($durationtime <= 60) {//在一分钟之内进行的
                $data['result'] = 'failed';
                $data['code'] = '1分钟之内请勿重复获取';
                return json_encode($data);
            }

             if (empty($telenumber)) {
                $data['result'] = 'failed';
                $data['code'] = 'error:手机号为空';
            } else {
                /*start: 每天每个手机号获取限制次数的验证码*/
                $telecode_info = \Yii::$app->cache->get('smscode_'.$telenumber);

                if ($telecode_info) {//缓存中已经存在此手机号的信息
                    $now = date('Y-m-d');
                    $codeinfo = unserialize($telecode_info);
                    $count = $codeinfo['count'] ? $codeinfo['count'] : 0;
                    $cachedate = $codeinfo['date'];
                    if ($now == $cachedate) {//当前的日期和缓存中该手机号的日期相同
                        if ($count >= $maxcount_code) {//是否超过每天限制的获取次数
                            $data['result'] = 'failed';
                            $data['code'] = '此手机号于今天已经获取' . $maxcount_code . '次验证码，禁止再次获取';
                            return json_encode($data);
                        }
                    } else {//缓存中的日期不是今天，更新获取次数为0，日期为今天
                        $count = 0;
                        $codeinfo = array(
                            'count' => $count,
                            'date' => $now
                        );
                        $codeinfoser = serialize($codeinfo);
                        \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
                    }
                } else {//缓存中不存在当前手机号的信息
                    /*
                     *保存次数和日期于缓存中
                     */
                    $codeinfo = array(
                        'count' => 0,
                        'date' => date('Y-m-d')
                    );
                    $codeinfoser = serialize($codeinfo);
                    \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
                }
                /*end: 每天每个手机号获取限制次数的验证码*/
                $code = $this->generateCode();
                //$content = "您的验证码是：【" . $code . "】。请不要把验证码泄露给其他人。";
                    if (!\Yii::$app->session->isActive) {
                        \Yii::$app->session->open();
                    }
                    $cur_session = \Yii::$app->session;
                    $cur_session->setTimeout(1800);//设置session的保存时间为5分钟，好像没有生效
                    $cur_session->set('login_sms_code', $code);
                    $cur_session->set('login_sms_time', time());
                    $data['result'] = 'success';
                    $res['telephone'] = $telenumber;
                    $res['code'] = $code;
                    $this->sendTelephoneValidateCode($res);//触发事件

                    /*start: 更新缓存中的获取验证码的次数加1*/
                    $phonecode = \Yii::$app->cache->get('smscode_'.$telenumber);
                    $phonecode = unserialize($phonecode);
                    $phonecode['count'] = $phonecode['count'] + 1;
                    $phonecode = serialize($phonecode);
                    \Yii::$app->cache->set('smscode_'.$telenumber, $phonecode, 3600 * 24);
                    /*end: 更新缓存中获取验证码的次数*/
            }
            return json_encode($data);
        }elseif($special_function=='durationtime'){
            $data = $this->getDurationTime();
            return json_encode($data);
        }

    }

    //生成验证码，纯数字的六位数字
    private function generateCode()
    {
        return rand(1000, 9999);
    }

    //发送短信的方法，传参数手机号+短信内容
    /**public function sendCode($telenum, $content)
    {//发送验证码的函数
        $data=['mobile'=>$telenum,'content'=>$content];
        FrontRest::sendMsg($data);
        return true;
    }*/
    /*通过ajax返回当前session中保存的验证码获取的时间，不对不能够是时间，而是当前后台系统时间和验证码保存时间的间隔值
    如果时间间隔为0-1分钟，返回秒数的倒计时
    如果时间间隔为1分钟开外，显示获取验证码的按钮
    */
    public function getDurationTime(){
        $nowtime = time();
        $signup_sms_time = \Yii::$app->session->get('login_sms_time')?\Yii::$app->session->get('login_sms_time'):0;
        $duration = $nowtime - $signup_sms_time;
        if($duration>0 && $duration<60){
            $data['result'] = 'countdown';
            $data['countdownnum'] = 60-$duration;
        }else{
            $data['result'] = 'nocountdown';
            $data['countdownnum'] = 0;
        }
        return $data;
    }

    //调用此方法触发发送短信的事件
    public function sendTelephoneValidateCode(array $res){
        $this->trigger(self::EVENT_SEND_TELEPHONE_VALIDATE_CODE, new ActionEvent(["data"=>$res]));
    }

    //重写行为
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), $this->behaviorsData);
    }


}